<template>
  <span>
    <el-upload
      action="demo"
      style="display:inline;"
      :show-file-list="false"
      :on-preview="handlePreview"
      :on-success="handleImportSuccess"
      :before-upload="beforeImport"
      :http-request="doImport"
      :auto-upload="true"
    >
      <el-button type="danger" class="btn">导入菜单</el-button>
    </el-upload>
  </span>
</template>

<script>
export default {
  name: 'ImportMenu',
  props: {
    fnImport: {
      type: Function,
      required: true
    }
  },
  methods: {
    doImport(upload) {
      const fileObject = upload.file
      // console.log(fileObject)
      this.fnImport(this, fileObject).then(res => {
        this.$success('菜单导入成功，请刷新页面')
      }).catch(err => {
        console.log(err)
      })
    },
    handleImportSuccess(res, file) {
      // console.log('handleAvatarSuccess')
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    handlePreview(file) {
      // console.log('preview')
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeImport(file) {
      // console.log('before')
      // console.log(file.type)
      const isJson = file.type === 'application/json'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJson) {
        this.$message.error('导入菜单必须是 json 格式!')
      }
      if (!isLt2M) {
        this.$message.error('菜单文件大小不能超过 2MB!')
      }
      return isJson && isLt2M
    }
  }
}
</script>
